package com.szjlc.blog.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.szjlc.blog.common.result.WebServiceResponse;
import com.szjlc.blog.entity.Blog;
import com.szjlc.blog.service.BlogService;
import com.szjlc.blog.util.ShiroUtil;
import java.util.Date;
import java.util.Objects;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.skywalking.apm.toolkit.trace.Tag;
import org.apache.skywalking.apm.toolkit.trace.Trace;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 博客控制层
 * @author steve
 * @since 2022-11-13
 */
@RestController
@RequestMapping(value = "/blogs")
public class BlogController {

    @Autowired
    private BlogService blogService;


    /** 获取当前页面数据 */
    @Trace
    @Tag(key = "blogs", value = "returnObj")
    @GetMapping(value = "/page/{currentPage}")
    public WebServiceResponse<IPage> blogs(@PathVariable("currentPage") Integer currentPage) {
        if (currentPage == null || currentPage < 1) {
            currentPage = 1;
        }
        int pageSize = 5;
        Page<Blog> page = new Page<>(currentPage, pageSize);
        IPage<Blog> pageData = blogService.page(page, new QueryWrapper<Blog>().orderByDesc("create_time"));
        return WebServiceResponse.success(pageData);
    }

    /** 获取详情页内容 */
    @Trace
    @Tag(key = "detail", value = "returnObj")
    @GetMapping(value = "/blog/{id}")
    public WebServiceResponse<Blog> detail(@PathVariable("id") Long id) {
        Blog blog = blogService.getById(id);
        Assert.notNull(blog, "该博客不存在！");
        return WebServiceResponse.success(blog);
    }

    /** 编辑或发布博客 */
    @RequiresAuthentication
    @PostMapping(value = "/blog/edit")
    public WebServiceResponse<Blog> edit(@RequestBody Blog blog) {
        Blog temp;
        if (blog.getId() != null) {
            temp = blogService.getById(blog.getId());
            Assert.isTrue(Objects.equals(temp.getUserId(), ShiroUtil.getProfile().getId()), "没有编辑权限");
        }
        else {
            temp = new Blog();
            temp.setUserId(ShiroUtil.getProfile().getId());
            temp.setCreateTime(new Date());
            temp.setStatus(0);
        }

        BeanUtil.copyProperties(blog,temp,"id","userId","createTime","status");
        blogService.saveOrUpdate(temp);
        return WebServiceResponse.success(temp);

    }


}
